<?php
/**
 * Enter description here...
 *
 * @package if
 * @subpackage module.helper.controllers
 * @since 1.0
 */
class IfHelperConfigDatabaseController extends IHelperController {
	function _init() {
		$names = array_keys(IDb::driverClasses());
		$this->drivers = array_combine($names, $names);
	}
	
	function doIndex() {
		$this->opts = $this->_opts(null);
		$this->_saveOpts(null);
	}
	
	function doDev() {
		$this->opts = $this->_opts("dev");
		$this->_saveOpts("dev");
	}
	
	function doTest() {
		$this->opts = $this->_opts("test");
		$this->_saveOpts("test");
	}
	
	function doProd() {
		$this->opts = $this->_opts("prod");
		$this->_saveOpts("prod");
	}
	
	function doDelete() {
		$env = x("env");
		$type = x("type");
		$dir = IApplication::singleton()->directory("config");
		$file = ($env != "index") ? $dir . "/_db_{$env}.php" : $dir . "/_db.php";
		
		//修改配置
		$config = new IConfig($file);
		$opts = $config->opts();
		unset($opts[$type]);
		$config->setOpts($opts);
		$config->write($file);
				
		//返回
		$this->redirect($env);
	}
	
	private function _opts($env) {
		$dir = IApplication::singleton()->directory("config");
		$file = $env ? $dir . "/_db_{$env}.php" : $dir . "/_db.php";
		$opts = array();
		if (is_file($file)) {
			$config = new IConfig($file);
			$opts = $config->opts();
			foreach ($opts as $key => $opt) {
				if (!isset($opt["driver"])) {
					unset($opts[$key]);
				}
			}
		}
		return $opts;
	}
	
	private function _saveOpts($env) {
		if (!$this->request()->isPost()) {
			return;
		}
		$dir = IApplication::singleton()->directory("config");
		$file = $env ? $dir . "/_db_{$env}.php" : $dir . "/_db.php";
		$opts = array();
		$config = new IConfig($file);
		$opts = $config->opts();
		$names = x("db");
		
		if (is_array($names)) {
			foreach ($names as $index => $name) {
				if ($index != "_new_") {
					unset($opts[$index]);
					$opts[$name] = xn($index);
				}
				else {
					if (x("_create_")) {
						$opts[$name] = xn("_new_");
					}
				}
			}
			
			//写回到文件
			$config->setOpts($opts);
			$config->write($file);
		}
		
		$this->redirect($env ? $env : "index");
	}
	
}


?>